// pages/clockoff/clockoff.js
var times = require('../../utils/time.js')
const {
    imgConfig,
    config
} = require('../../utils/config.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        todayClick: true,
        imgUrl: `${imgConfig}`,
        statusBarHeight: app.globalData.statusBarHeight,
        flag: [5, 0, 0],
        startext: ['非常满意', '', '', ],
        starsBox: [1, 2, 3, 4, 5],
        teaIndex: '',
        num: 5,
        remarks: '',
        time: times.formatTime(new Date()),
        courseChapterList: '',
        chapterList: '',
        chapterIndex: app.globalData.chapterIndex,
        courseIndex: app.globalData.courseIndex,
        courseId: '',
        chapterId: ''

    },
    back: function () {
        wx.navigateBack({});
    },
    //remarks输入双向数据绑定
    remarksInput: function (e) {
        this.setData({
            remarks: e.detail.value
        })
    },
    /**
     * 星级评分 获取当前选中的是几颗星 num
     */
    changePic: function (e) {
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.no;
        var a = 'flag[' + index + ']';
        var b = 'startext[' + index + ']';
        var that = this;
        if (num == 1) {
            that.setData({
                num: num,
                [a]: 1,
                [b]: '非常不满意'
            });
        } else if (num == 2) {
            that.setData({
                num: num,
                [a]: 2,
                [b]: '不满意'
            });
        } else if (num == 3) {
            that.setData({
                num: num,
                [a]: 3,
                [b]: '一般'
            });
        } else if (num == 4) {
            that.setData({
                num: num,
                [a]: 4,
                [b]: '满意'
            });
        } else if (num == 5) {
            that.setData({
                num: num,
                [a]: 5,
                [b]: '非常满意'
            });
        }
    },
    goLcaClock(){
      var that = this
      console.log(app.globalData.clockStatus)
      if (!app.globalData.clockStatus) {
        wx.showToast({
            title: '请先进行上课打卡!',
            icon: 'none'
        })
        return
    }
    if (this.data.remarks === "" || this.data.num === "") {
        wx.showToast({
            title: '请填写评价!',
            icon: 'none'
        })
        return
    }
    app.globalData.evaluate = that.data.remarks
    app.globalData.score = that.data.num
      wx.navigateTo({
        url: '/pages/lcaClock/lcaClock?status=1',
      })
    },
    /**
     * 打卡 发送请求
     */
    punchTheClock: function () {
        var that = this
        console.log(this.data.chapterIndex)
        if (this.data.chapterIndex === undefined || this.data.courseIndex === undefined ){
            wx.showToast({
                title: '请选择课程章节!',
                icon: 'none'
            })
            return
        }
        if (!app.globalData.clockStatus) {
            wx.showToast({
                title: '请先进行上课打卡!',
                icon: 'none'
            })
            return
        }
        if (this.data.remarks === "" || this.data.num === "") {
            wx.showToast({
                title: '请填写评价!',
                icon: 'none'
            })
            return
        }
        var studentInfo = app.globalData.userInfo
        //当前为下课打卡
            var clockStatus = 1
            var score = that.data.num
        //打卡确认
        wx.showModal({
            title: '提示',
            content: '是否确认打卡?',
            success(res) {
                if (res.confirm) {
                    wx.showToast({
                        title: '打卡成功',
                        duration: 1000
                    })
                    wx.request({
                        url: `${config}/wechat/wxclock/saveClock`,
                        method: 'post',
                        data: {
                            evaluate: that.data.remarks,
                            score: score,
                            stuId: studentInfo.id,
                            courseId: that.data.courseId,
                            chapterId: that.data.chapterId,
                            clockStatus: clockStatus
                        },
                        success(resp) {
                            setTimeout(function () {
                                wx.switchTab({
                                    url: '/pages/my/my',
                                })
                                //打卡成功修改打卡状态
                                if (resp.data.code == 0) {
                                    that.setData({
                                        todayClick: true
                                    })
                                }
                            }, 1000)
                        }
                    }) //请求结束
                } else if (res.cancel) {
                    wx.showToast({
                        title: '已取消打卡!',
                        icon: 'none',
                        duration: 1000
                    })
                }
            }
        })
    },
    //选择课程 修改索引
    listenerCoursePickerSelected: function (e) {
        //改变index值，通过setData()方法重绘界面
        var that = this
        this.setData({
            courseIndex: e.detail.value,
            chapterList: that.data.courseChapterList[e.detail.value].chapter,
            courseId: that.data.courseChapterList[e.detail.value].id,
            //课程更改 清空章节列表索引
            chapterIndex: ''
        });
        console.log("选取课程Id:", that.data.courseId)
    },
    //选择章节 修改索引
    listenerChapterPickerSelected: function (e) {
        //改变index值，通过setData()方法重绘界面
        var that = this
        this.setData({
            chapterIndex: e.detail.value,
            chapterId: that.data.chapterList[e.detail.value].id
        });
        console.log("选取章节Id:", that.data.chapterId)
    },
    /**
     * 页面当前时间定时器
     */
    timeInterval() {
        //打卡组件  显示当前时间定时器
        setInterval(() => {
            var date = times.formatTime(new Date());
            this.setData({
                time: date,
            })
        }, 1000)
    },
    /**
     * 获取课程、章节信息
     */
    getCourseChapterList() {
        var that = this;
        //发送获取课程信息的请求
        wx.request({
            url: `${config}/wechat/wxclock/getCourseChapterList`,
            data: {
                majorId: app.globalData.userInfo.majorId
            },
            success(resp) {
                //课程信息赋值给前台
                that.setData({
                    courseChapterList: resp.data.courseChapterList,
                })
                //判断是否有打卡记录 没有则不对章节赋值
                if (app.globalData.courseIndex === undefined || app.globalData.chapterIndex === undefined ){
                    return
                }
                //通过后台获取的打卡记录 选取对应的章节列表 赋值课程列表索引
                var courseIndex = app.globalData.courseIndex
                var courseLength = that.data.courseChapterList.length
                that.setData({
                    chapterList: resp.data.courseChapterList[courseIndex].chapter,
                })
                /* 小程序获取数据全部都是异步的 数组必须先存在才能获取长度 */
                var chapterLength = that.data.chapterList.length
                var chapterIndex = app.globalData.chapterIndex
                //通过后台获取打卡记录 自动选取下一节打卡课程
                var clockStatus = app.globalData.clockStatus //获取最后打卡为上课/下课
                that.setData({
                    clockStatus: clockStatus
                })
                //判断最后一次打卡为下课打卡且章节是最后一个章节 课程不是最后一个课程  章节索引变为0 课程索引加1
                if (chapterIndex + 1 >= chapterLength && courseIndex + 1 < courseLength && clockStatus === 1) {
                    chapterIndex = 0
                    courseIndex += 1
                } //章节不是最后一个  章节索引加1 
                else if (chapterIndex + 1 < chapterLength && clockStatus === 1) {
                    chapterIndex += 1
                }
                //章节为最后一章 章节索引为最大值
                if (courseIndex + 1 == courseLength && clockStatus === 1) {
                    courseIndex = courseLength - 1
                    //章节 课程都为最后一个 章节索引 课程索引都为最大值
                } else if (courseIndex + 1 >= courseLength && chapterIndex + 1 >= chapterLength && clockStatus === 1) {
                    courseIndex = courseLength - 1
                    chapterIndex = chapterLength - 1
                }
                console.log('chapterIndex:', chapterIndex)
                console.log('courseIndex:', courseIndex)
                that.setData({
                    chapterList: resp.data.courseChapterList[courseIndex].chapter,
                    courseIndex: courseIndex,
                    chapterIndex: chapterIndex,
                    courseId: resp.data.courseChapterList[courseIndex].id,
                    chapterId: resp.data.courseChapterList[courseIndex].chapter[chapterIndex].id
                })
                console.log("课程Id:", that.data.courseId, ",章节Id:", that.data.chapterId)
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.timeInterval()
        this.getCourseChapterList()
        
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        this.setData({
            avatar: app.globalData.userInfo.photo, //头像
            stuName: app.globalData.userInfo.stuName, //姓名
            phoneNumber: app.globalData.userInfo.stuTel, //手机号
        })
        this.getLastClock()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 获取最新打卡参数
     */
    getLastClock() {
        var that = this
        //Storage中存入新的打卡数据 用于返回后访问打卡页使用
        wx.request({
            url: `${config}/wechat/wxclock/getLastClock`,
            data: {
                stuId: app.globalData.userInfo.id
            },
            success(res) {
                if (res.data.clockEntity == null || res.data.clockEntity == undefined) {
                    return
                }
                if(res.data.clockEntity.updateTime == null){
                  var clockStatus = true
                }else{
                  var clockStatus = false
                }
                
                var courseId = res.data.clockEntity.courseId
                var chapterId = res.data.clockEntity.chapterId
                var courseChapterList = that.data.courseChapterList
                for (var i = 0; i < courseChapterList.length; i++) {
                    if (courseChapterList[i].id == courseId) {
                        that.setData({
                            courseIndex: i
                        })
                    }

                }
                var chapterList = that.data.courseChapterList[app.globalData.courseIndex].chapter
                for (var i = 0; i < chapterList.length; i++) {
                    if (chapterList[i].id == chapterId) {
                        that.setData({
                            chapterIndex: i
                        })
                    }

                }
                app.globalData.clockStatus = clockStatus //添加打卡状态 页面显示 上课/下课打卡
                app.globalData.chapterIndex = that.data.chapterIndex//添加章节列表索引
                app.globalData.courseIndex = that.data.courseIndex //添加课程列表索引
            }
        })
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})